package com.sk.cardeal.act.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sk.cardeal.R;
import com.sk.cardeal.act.home.fragment.AlreadyPayFragment;
import com.sk.cardeal.act.home.fragment.AlreadyReachFragment;
import com.sk.cardeal.adapter.AlreadyUploadAdapter;
import com.sk.cardeal.adapter.PicAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.utils.HttpAddress;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.UpLoadUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2018/1/10.
 */

public class UpLoadPictureActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.type_img)
    ImageView typeImg;
    @BindView(R.id.car_num)
    TextView carNum;
    @BindView(R.id.pic_ryc)
    RecyclerView picRyc;
    @BindView(R.id.already_ryc)
    RecyclerView alreadyRyc;

    private PicAdapter adapter;
    private AlreadyUploadAdapter alreadyUploadAdapter;
    private List<LocalMedia> allDataList = new ArrayList<>();
    private List<LocalMedia> pictureList = new ArrayList<>();

    private StringBuilder sb = new StringBuilder();
    private int count;
    private LoadingDialog loadingDialog;

    private String url;
    private String brandUrl = "";

    @Override
    protected int getContentView() {
        return R.layout.activity_upload_picture;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String carNumString = getIntent().getStringExtra("carNum");
        carNum.setText(carNumString);

        brandUrl = getIntent().getStringExtra("brandUrl");
        url = getIntent().getStringExtra("url");
        allDataList = getIntent().getParcelableArrayListExtra("data");
        String[] strings;
        List<String> stringList = new ArrayList<>();

        if (url != null && url.length() > 0) {
            strings = url.split(",");
            stringList.addAll(Arrays.asList(strings));
        }

        Glide.with(mContext).load(brandUrl).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(typeImg);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        allDataList.add(new LocalMedia());
        picRyc.setLayoutManager(new GridLayoutManager(this, 5));
        adapter = new PicAdapter(R.layout.item_release_pic, allDataList);
        picRyc.setAdapter(adapter);
        adapter.setOnItemClickListener(this);

        alreadyRyc.setLayoutManager(new GridLayoutManager(this, 5));
        alreadyUploadAdapter = new AlreadyUploadAdapter(R.layout.item_release_pic, stringList);
        alreadyRyc.setAdapter(alreadyUploadAdapter);
        alreadyUploadAdapter.setOnItemClickListener(this);

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof PicAdapter) {
            if (position == allDataList.size() - 1) {
                PictureSelector.create(UpLoadPictureActivity.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .maxSelectNum(9)// 最大图片选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(true)// 是否可预览图片 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                        .enableCrop(false)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .compressSavePath(Environment.getExternalStorageDirectory().getPath())//压缩图片保存地址
                        .selectionMedia(pictureList)// 是否传入已选图片 List<LocalMedia> list
                        .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
            }
        } else if (adapter instanceof AlreadyUploadAdapter) {

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    try {
                        // 图片选择结果回调
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                        pictureList.clear();
                        pictureList.addAll(selectList);
                        allDataList.clear();
                        allDataList.addAll(pictureList);
                        allDataList.add(new LocalMedia());
                        adapter.notifyDataSetChanged();
                        break;
                    } catch (Exception e) {
                        Log.e("onActivityResult",e.toString());
                    }

            }
        }
    }


    @OnClick({R.id.back, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.save:
                if (pictureList.size() > 0) {
                    loadingDialog.show();
                    count = 1;
                    if (pictureList.get(0).isCompressed()) {
                        UpLoadUtils.uploadPicTask(pictureList.get(0).getCompressPath(), UpLoadPictureActivity.this);
                    } else {
                        UpLoadUtils.uploadPicTask(pictureList.get(0).getPath(), UpLoadPictureActivity.this);
                    }

                } else {
                    Toast.makeText(mContext, "您尚未选择上传的图片！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void success(final String path) {
        super.success(path);
        Log.v("success", path);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (count == pictureList.size()) {
                    loadingDialog.cancelDialog();
                    Log.v("success", path);
                    sb.append(path);
                    Intent intent = new Intent();
                    if (url != null && url.length() > 0) {
                        intent.putExtra("url", url + "," + sb.toString());
                        pictureList.clear();
                        intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) pictureList);
                    } else {
                        intent.putExtra("url", sb.toString());
                        pictureList.clear();
                        intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) pictureList);
                    }
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    sb.append(path).append(",");
                    count++;
                    if (pictureList.get(count - 1).isCompressed()) {
                        UpLoadUtils.uploadPicTask(pictureList.get(count - 1).getCompressPath(), UpLoadPictureActivity.this);
                    } else {
                        UpLoadUtils.uploadPicTask(pictureList.get(count - 1).getPath(), UpLoadPictureActivity.this);
                    }

                }
            }
        });


    }

    @Override
    public void fail() {
        super.fail();
    }
}
